package com.tanhua.locationmanager.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.domain.db.Admin;
import com.tanhua.dubbo.api.db.AdminApi;
import com.tanhua.locationmanager.constants.Constants;
import com.tanhua.locationmanager.exceptions.TanhuaException;
import com.tanhua.locationmanager.interceptors.AdminHolder;
import com.tanhua.locationmanager.util.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginService {

    @Reference
    private AdminApi adminApi;


    private final RestTemplate restTemplate;
    private final AipFaceTemplate aipFaceTemplate;
    private final StringRedisTemplate redisTemplate;

    public LoginService(RestTemplate restTemplate, AipFaceTemplate aipFaceTemplate, StringRedisTemplate redisTemplate) {
        this.restTemplate = restTemplate;
        this.aipFaceTemplate = aipFaceTemplate;
        this.redisTemplate = redisTemplate;
    }

    public String wechatLogin(String code, RedirectAttributes redirectAttributes) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3bdb1192c22883f3&secret=db9d6b88821df403e5ff11742e799105&code=" + code + "&grant_type=authorization_code";
        ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
        Map<String,String> map = JSON.parseObject(entity.getBody(),Map.class);
        String openid = map.get("openid");
        redisTemplate.boundValueOps("CURRENT_WECHAT_OPENID").set(openid);
        Admin admin = adminApi.findByOpenid(openid);
        if (admin == null) {
            return "redirect:http://192.168.131.61:8089/binding.html";
        }
        String token = JwtUtils.createToken(admin.getUsername(),admin.getId(),"tanhua");
        redisTemplate.boundValueOps(Constants.CACHE_KEY_TOKEN_PREFIX + token).set(JSON.toJSONString(admin));
        redirectAttributes.addAttribute("Authorization",token);
        return "redirect:http://192.168.131.61:8089/index.html";
    }

    public ResponseEntity<?> faceLogin(MultipartFile imageBase64) throws IOException {
        Long userId = aipFaceTemplate.isRegister(imageBase64.getBytes());
        if (userId == null) {
            throw new TanhuaException(500,"用户不存在");
        }
        Admin admin = adminApi.findById(userId);
        String token = JwtUtils.createToken(admin.getUsername(),admin.getId(),"tanhua");
        redisTemplate.boundValueOps(Constants.CACHE_KEY_TOKEN_PREFIX + token).set(JSON.toJSONString(admin));
        return ResponseEntity.ok(token);
    }

    public ResponseEntity<?> passwordLogin(String username, String password, String verificationCode, String uuid) {
        String code = redisTemplate.boundValueOps(Constants.CACHE_KEY_CAP_PREFIX + uuid).get();
        if (code == null)
            throw new TanhuaException(500,"验证码超时");
        if (!code.equals(verificationCode))
            throw new TanhuaException(500,"验证码错误");
        Admin admin = adminApi.findByUsername(username);
        if (admin == null)
            throw new TanhuaException(500,"用户不存在");
        if (!admin.getPassword().equals(DigestUtils.md5Hex(password)))
            throw new TanhuaException(500,"密码错误");
        String token = JwtUtils.createToken(admin.getUsername(),admin.getId(),"tanhua");
        redisTemplate.boundValueOps(Constants.CACHE_KEY_TOKEN_PREFIX + token).set(JSON.toJSONString(admin));
        return ResponseEntity.ok(token);
    }

    public ResponseEntity<?> verification(String uuid, HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(130,50);
        lineCaptcha.write(response.getOutputStream());
        redisTemplate.boundValueOps(Constants.CACHE_KEY_CAP_PREFIX + uuid).set(lineCaptcha.getCode(),10, TimeUnit.MINUTES);
        return ResponseEntity.ok().build();
    }

    public ResponseEntity<?> logout() {
        String token = AdminHolder.getAdmin().getToken();
        redisTemplate.delete(Constants.CACHE_KEY_TOKEN_PREFIX + token);
        return ResponseEntity.ok().build();
    }

    public ResponseEntity<?> bind(String username, String password) {
        Admin admin = adminApi.findByUsername(username);
        if (admin == null)
            throw new TanhuaException(500,"用户不存在");
        if (!admin.getPassword().equals(DigestUtils.md5Hex(password)))
            throw new TanhuaException(500,"密码错误");
        String wechatOpenid = redisTemplate.boundValueOps("CURRENT_WECHAT_OPENID").get();
        if (wechatOpenid == null)
            throw new TanhuaException(500,"密码错误");
        adminApi.bindWechat(wechatOpenid,admin);
        Map<String,String> result = new HashMap<>();
        result.put("msg","绑定成功，欢迎您" + admin.getUsername());
        String token = JwtUtils.createToken(admin.getUsername(),admin.getId(),"tanhua");
        redisTemplate.boundValueOps(Constants.CACHE_KEY_TOKEN_PREFIX + token).set(JSON.toJSONString(admin));
        result.put("token",token);
        return ResponseEntity.ok(result);
    }
}
